package bean;

import bbdd.Conexion;
import utilidades.Encriptacion;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

/**
 * Created by juanky on 5/12/14.
 */
public class BeanSession {
    private Integer userId;
    private Integer sessionId;
    private Integer errorLogin;
    private Boolean activo;
    private Integer rolId;

    public BeanSession() {
        this.userId = 0;
        this.sessionId = 0;
        this.errorLogin = 0;
        this.activo = false;
        this.rolId = 0;
    }

    public boolean login(String username_new_txt, String password_new_txt) {
        Conexion cnx = new Conexion();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String select = "select id, rol from usuarios where nick=? and password=?";
        String insertOk = "insert into login (usuario, dispositivo, fecha) values (?,1,?)";
        String insertKo = "insert into login (nick, bad_password, dispositivo, fecha) values (?,?,1,?)";
        Encriptacion encriptacion = new Encriptacion();
        try {
            ps = cnx.getConexion(select);
            ps.setString(1, username_new_txt);
            ps.setString(2, encriptacion.encriptar(password_new_txt));
            rs = ps.executeQuery();
            if (rs.next()) {
                this.userId = rs.getInt(1);
                this.rolId = rs.getInt(2);
                rs.close();
                ps.close();
                ps = cnx.getConexion(insertOk, new String[]{"id"});
                ps.setInt(1, this.userId);
                ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
                ps.execute();
                rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    this.sessionId = rs.getInt(1);
                    this.activo = true;
                } else {
                    this.errorLogin = 1;
                }
            } else {
                rs.close();
                ps.close();
                ps = cnx.getConexion(insertKo, new String[]{"id"});
                ps.setString(1, username_new_txt);
                ps.setString(2, password_new_txt);
                ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
                ps.execute();
                this.errorLogin = 2;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Conexion.close(cnx, ps, rs);
        }
        return (this.errorLogin == 0);
    }

    public Boolean isActivo() {
        return activo;
    }

    public void setActivo(boolean activo) {
        this.activo = activo;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public Integer getRolId() {
        return rolId;
    }

    public void setRolId(Integer rolId) {
        this.rolId = rolId;
    }
}
